package cn.iocoder.yudao.module.eval.controller.admin.employee;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.framework.apilog.core.annotation.ApiAccessLog;
import cn.iocoder.yudao.module.eval.controller.admin.employee.vo.*;
import cn.iocoder.yudao.module.eval.dal.dataobject.employee.EvalEmployeeProfileDO;
import cn.iocoder.yudao.module.eval.dal.dataobject.employee.EvalEmployeeWorkHistoryDO;
import cn.iocoder.yudao.module.eval.dal.dataobject.employee.EvalEmployeeTrainingRecordDO;
import cn.iocoder.yudao.module.eval.service.employee.EvalEmployeeService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.Collection;
import java.util.List;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.apilog.core.enums.OperateTypeEnum.*;

@Tag(name = "管理后台 - 企业员工管理")
@RestController
@RequestMapping("/eval/employee")
@Validated
@Slf4j
public class EvalEmployeeController {

    @Resource
    private EvalEmployeeService employeeService;

    // ==================== 员工基础管理 ====================

    @PostMapping("/create")
    @Operation(summary = "创建员工")
    @PreAuthorize("@ss.hasPermission('eval:employee:create')")
    @ApiAccessLog(operateType = CREATE)
    public CommonResult<Long> createEmployee(@Valid @RequestBody EvalEmployeeCreateReqVO createReqVO) {
        return success(employeeService.createEmployee(createReqVO));
    }

    @PutMapping("/update")
    @Operation(summary = "更新员工信息")
    @PreAuthorize("@ss.hasPermission('eval:employee:update')")
    @ApiAccessLog(operateType = UPDATE)
    public CommonResult<Boolean> updateEmployee(@Valid @RequestBody EvalEmployeeUpdateReqVO updateReqVO) {
        employeeService.updateEmployee(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除员工")
    @Parameter(name = "id", description = "员工ID", required = true)
    @PreAuthorize("@ss.hasPermission('eval:employee:delete')")
    @ApiAccessLog(operateType = DELETE)
    public CommonResult<Boolean> deleteEmployee(@RequestParam("id") Long id) {
        employeeService.deleteEmployee(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得员工详情")
    @Parameter(name = "id", description = "员工ID", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('eval:employee:query')")
    public CommonResult<EvalEmployeeRespVO> getEmployee(@RequestParam("id") Long id) {
        EvalEmployeeRespVO employee = employeeService.getEmployee(id);
        return success(employee);
    }

    @GetMapping("/list")
    @Operation(summary = "获得员工列表")
    @Parameter(name = "ids", description = "员工ID列表", required = true, example = "1024,2048")
    @PreAuthorize("@ss.hasPermission('eval:employee:query')")
    public CommonResult<List<EvalEmployeeRespVO>> getEmployeeList(@RequestParam("ids") Collection<Long> ids) {
        List<EvalEmployeeRespVO> list = employeeService.getEmployeeList(ids);
        return success(list);
    }

    @GetMapping("/page")
    @Operation(summary = "获得员工分页")
    @PreAuthorize("@ss.hasPermission('eval:employee:query')")
    public CommonResult<PageResult<EvalEmployeeRespVO>> getEmployeePage(@Valid EvalEmployeePageReqVO pageReqVO) {
        PageResult<EvalEmployeeRespVO> pageResult = employeeService.getEmployeePage(pageReqVO);
        return success(pageResult);
    }

    @GetMapping("/export-excel")
    @Operation(summary = "导出员工 Excel")
    @PreAuthorize("@ss.hasPermission('eval:employee:export')")
    @ApiAccessLog(operateType = EXPORT)
    public void exportEmployeeExcel(@Valid EvalEmployeePageReqVO pageReqVO,
                                   HttpServletResponse response) throws IOException {
        employeeService.exportEmployeeExcel(pageReqVO, response);
    }

    @PostMapping("/import-excel")
    @Operation(summary = "批量导入员工")
    @Parameter(name = "file", description = "Excel 文件", required = true)
    @PreAuthorize("@ss.hasPermission('eval:employee:import')")
    @ApiAccessLog(operateType = IMPORT)
    public CommonResult<EvalEmployeeImportResultRespVO> importEmployeeExcel(@RequestParam("file") MultipartFile file) throws Exception {
        EvalEmployeeImportResultRespVO result = employeeService.importEmployeeExcel(file);
        return success(result);
    }

    @GetMapping("/import-template")
    @Operation(summary = "获得导入员工模板")
    @PreAuthorize("@ss.hasPermission('eval:employee:import')")
    public void importEmployeeTemplate(HttpServletResponse response) throws IOException {
        employeeService.importEmployeeTemplate(response);
    }

    @GetMapping("/search")
    @Operation(summary = "搜索员工")
    @Parameter(name = "keyword", description = "搜索关键词", required = true)
    @Parameter(name = "deptId", description = "部门ID", required = false)
    @Parameter(name = "employeeStatus", description = "员工状态", required = false)
    @PreAuthorize("@ss.hasPermission('eval:employee:query')")
    public CommonResult<List<EvalEmployeeRespVO>> searchEmployees(@RequestParam("keyword") String keyword,
                                                                 @RequestParam(value = "deptId", required = false) Long deptId,
                                                                 @RequestParam(value = "employeeStatus", required = false) Integer employeeStatus) {
        List<EvalEmployeeRespVO> list = employeeService.searchEmployees(keyword, deptId, employeeStatus);
        return success(list);
    }

    // ==================== 考评员管理 ====================

    @PostMapping("/evaluator/set")
    @Operation(summary = "设置考评员资质")
    @PreAuthorize("@ss.hasPermission('eval:employee:evaluator')")
    @ApiAccessLog(operateType = UPDATE)
    public CommonResult<Boolean> setEvaluatorQualification(@Valid @RequestBody EvalEvaluatorQualificationSetReqVO setReqVO) {
        employeeService.setEvaluatorQualification(setReqVO);
        return success(true);
    }

    @PutMapping("/evaluator/update")
    @Operation(summary = "更新考评员资质")
    @PreAuthorize("@ss.hasPermission('eval:employee:evaluator')")
    @ApiAccessLog(operateType = UPDATE)
    public CommonResult<Boolean> updateEvaluatorQualification(@Valid @RequestBody EvalEvaluatorQualificationUpdateReqVO updateReqVO) {
        employeeService.updateEvaluatorQualification(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/evaluator/cancel/{userId}")
    @Operation(summary = "取消考评员资质")
    @Parameter(name = "userId", description = "用户ID", required = true)
    @PreAuthorize("@ss.hasPermission('eval:employee:evaluator')")
    @ApiAccessLog(operateType = DELETE)
    public CommonResult<Boolean> cancelEvaluatorQualification(@PathVariable("userId") Long userId) {
        employeeService.cancelEvaluatorQualification(userId);
        return success(true);
    }

    @GetMapping("/evaluator/page")
    @Operation(summary = "查询考评员列表")
    @PreAuthorize("@ss.hasPermission('eval:employee:query')")
    public CommonResult<PageResult<EvalEvaluatorRespVO>> getEvaluatorPage(@Valid EvalEvaluatorPageReqVO pageReqVO) {
        PageResult<EvalEvaluatorRespVO> pageResult = employeeService.getEvaluatorPage(pageReqVO);
        return success(pageResult);
    }

    @GetMapping("/evaluator/{userId}/workload")
    @Operation(summary = "查询考评员工作量")
    @Parameter(name = "userId", description = "用户ID", required = true)
    @Parameter(name = "startDate", description = "开始日期", required = false)
    @Parameter(name = "endDate", description = "结束日期", required = false)
    @PreAuthorize("@ss.hasPermission('eval:employee:query')")
    public CommonResult<EvalEvaluatorWorkloadRespVO> getEvaluatorWorkload(
            @PathVariable("userId") Long userId,
            @RequestParam(value = "startDate", required = false) String startDate,
            @RequestParam(value = "endDate", required = false) String endDate) {
        EvalEvaluatorWorkloadRespVO workload = employeeService.getEvaluatorWorkload(userId, startDate, endDate);
        return success(workload);
    }

    // ==================== 督导员管理 ====================

    @PostMapping("/supervisor/set")
    @Operation(summary = "设置督导员资质")
    @PreAuthorize("@ss.hasPermission('eval:employee:supervisor')")
    @ApiAccessLog(operateType = UPDATE)
    public CommonResult<Boolean> setSupervisorQualification(@Valid @RequestBody EvalSupervisorQualificationSetReqVO setReqVO) {
        employeeService.setSupervisorQualification(setReqVO);
        return success(true);
    }

    @PutMapping("/supervisor/update")
    @Operation(summary = "更新督导员资质")
    @PreAuthorize("@ss.hasPermission('eval:employee:supervisor')")
    @ApiAccessLog(operateType = UPDATE)
    public CommonResult<Boolean> updateSupervisorQualification(@Valid @RequestBody EvalSupervisorQualificationUpdateReqVO updateReqVO) {
        employeeService.updateSupervisorQualification(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/supervisor/cancel/{userId}")
    @Operation(summary = "取消督导员资质")
    @Parameter(name = "userId", description = "用户ID", required = true)
    @PreAuthorize("@ss.hasPermission('eval:employee:supervisor')")
    @ApiAccessLog(operateType = DELETE)
    public CommonResult<Boolean> cancelSupervisorQualification(@PathVariable("userId") Long userId) {
        employeeService.cancelSupervisorQualification(userId);
        return success(true);
    }

    @GetMapping("/supervisor/page")
    @Operation(summary = "查询督导员列表")
    @PreAuthorize("@ss.hasPermission('eval:employee:query')")
    public CommonResult<PageResult<EvalSupervisorRespVO>> getSupervisorPage(@Valid EvalSupervisorPageReqVO pageReqVO) {
        PageResult<EvalSupervisorRespVO> pageResult = employeeService.getSupervisorPage(pageReqVO);
        return success(pageResult);
    }

    // ==================== 工作经历管理 ====================

    @PostMapping("/work-history")
    @Operation(summary = "添加工作经历")
    @PreAuthorize("@ss.hasPermission('eval:employee:update')")
    @ApiAccessLog(operateType = CREATE)
    public CommonResult<Long> addWorkHistory(@Valid @RequestBody EvalEmployeeWorkHistorySaveReqVO saveReqVO) {
        return success(employeeService.addWorkHistory(saveReqVO));
    }

    @PutMapping("/work-history/{historyId}")
    @Operation(summary = "更新工作经历")
    @Parameter(name = "historyId", description = "经历ID", required = true)
    @PreAuthorize("@ss.hasPermission('eval:employee:update')")
    @ApiAccessLog(operateType = UPDATE)
    public CommonResult<Boolean> updateWorkHistory(@PathVariable("historyId") Long historyId,
                                                   @Valid @RequestBody EvalEmployeeWorkHistorySaveReqVO updateReqVO) {
        updateReqVO.setId(historyId);
        employeeService.updateWorkHistory(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/work-history/{historyId}")
    @Operation(summary = "删除工作经历")
    @Parameter(name = "historyId", description = "经历ID", required = true)
    @PreAuthorize("@ss.hasPermission('eval:employee:update')")
    @ApiAccessLog(operateType = DELETE)
    public CommonResult<Boolean> deleteWorkHistory(@PathVariable("historyId") Long historyId) {
        employeeService.deleteWorkHistory(historyId);
        return success(true);
    }

    @GetMapping("/work-history/user/{userId}")
    @Operation(summary = "获取员工工作经历")
    @Parameter(name = "userId", description = "用户ID", required = true)
    @PreAuthorize("@ss.hasPermission('eval:employee:query')")
    public CommonResult<List<EvalEmployeeWorkHistoryRespVO>> getWorkHistoryByUser(@PathVariable("userId") Long userId) {
        List<EvalEmployeeWorkHistoryDO> list = employeeService.getWorkHistoryByUser(userId);
        return success(BeanUtils.toBean(list, EvalEmployeeWorkHistoryRespVO.class));
    }

    // ==================== 培训记录管理 ====================

    @PostMapping("/training")
    @Operation(summary = "添加培训记录")
    @PreAuthorize("@ss.hasPermission('eval:employee:training')")
    @ApiAccessLog(operateType = CREATE)
    public CommonResult<Long> addTrainingRecord(@Valid @RequestBody EvalEmployeeTrainingRecordSaveReqVO saveReqVO) {
        return success(employeeService.addTrainingRecord(saveReqVO));
    }

    @PutMapping("/training/{trainingId}")
    @Operation(summary = "更新培训记录")
    @Parameter(name = "trainingId", description = "培训ID", required = true)
    @PreAuthorize("@ss.hasPermission('eval:employee:training')")
    @ApiAccessLog(operateType = UPDATE)
    public CommonResult<Boolean> updateTrainingRecord(@PathVariable("trainingId") Long trainingId,
                                                      @Valid @RequestBody EvalEmployeeTrainingRecordSaveReqVO updateReqVO) {
        updateReqVO.setId(trainingId);
        employeeService.updateTrainingRecord(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/training/{trainingId}")
    @Operation(summary = "删除培训记录")
    @Parameter(name = "trainingId", description = "培训ID", required = true)
    @PreAuthorize("@ss.hasPermission('eval:employee:training')")
    @ApiAccessLog(operateType = DELETE)
    public CommonResult<Boolean> deleteTrainingRecord(@PathVariable("trainingId") Long trainingId) {
        employeeService.deleteTrainingRecord(trainingId);
        return success(true);
    }

    @GetMapping("/training/user/{userId}")
    @Operation(summary = "获取员工培训记录")
    @Parameter(name = "userId", description = "用户ID", required = true)
    @PreAuthorize("@ss.hasPermission('eval:employee:query')")
    public CommonResult<PageResult<EvalEmployeeTrainingRecordRespVO>> getTrainingRecordsByUser(
            @PathVariable("userId") Long userId,
            @Valid EvalEmployeeTrainingRecordPageReqVO pageReqVO) {
        pageReqVO.setUserId(userId);
        PageResult<EvalEmployeeTrainingRecordDO> pageResult = employeeService.getTrainingRecordPage(pageReqVO);
        return success(BeanUtils.toBean(pageResult, EvalEmployeeTrainingRecordRespVO.class));
    }

    // ==================== 统计分析 ====================

    @GetMapping("/statistics/overview")
    @Operation(summary = "员工概况统计")
    @PreAuthorize("@ss.hasPermission('eval:employee:query')")
    public CommonResult<EvalEmployeeStatisticsRespVO> getEmployeeStatistics() {
        EvalEmployeeStatisticsRespVO statistics = employeeService.getEmployeeStatistics();
        return success(statistics);
    }

    @GetMapping("/statistics/department")
    @Operation(summary = "部门员工分布统计")
    @PreAuthorize("@ss.hasPermission('eval:employee:query')")
    public CommonResult<List<EvalEmployeeDepartmentStatisticsRespVO>> getDepartmentStatistics() {
        List<EvalEmployeeDepartmentStatisticsRespVO> statistics = employeeService.getDepartmentStatistics();
        return success(statistics);
    }

    @GetMapping("/statistics/education")
    @Operation(summary = "学历分布统计")
    @PreAuthorize("@ss.hasPermission('eval:employee:query')")
    public CommonResult<List<EvalEmployeeEducationStatisticsRespVO>> getEducationStatistics() {
        List<EvalEmployeeEducationStatisticsRespVO> statistics = employeeService.getEducationStatistics();
        return success(statistics);
    }

}
